package com.fyt.reachgo.interceptor;


import com.fyt.reachgo.domain.dto.UserDTO;
import com.fyt.reachgo.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 放行所有OPTIONS请求（预检请求）
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 2. 检查用户登录状态
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            log.warn("用户未登录，请求路径: {}", request.getRequestURI());

            // 3. 动态设置CORS头（避免硬编码*）
            String origin = request.getHeader("Origin");
            response.setHeader("Access-Control-Allow-Origin", origin != null ? origin : "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Expose-Headers", "Authorization");

            // 4. 返回401 JSON响应
            response.setStatus(401);
            response.setContentType("application/json");
            response.getWriter().write("{\"code\":401, \"message\":\"未授权\"}");
            return false;
        }
        return true;
    }

    // 后置拦截器
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
